/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lucava.boatskeeper.server.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import org.lucava.boatskeeper.server.entity.Boat;
import org.lucava.boatskeeper.shared.dto.BoatDto;
import org.lucava.boatskeeper.shared.dto.BoatImageDto;
import org.lucava.boatskeeper.shared.dto.CategoryDto;

/**
 *
 * @author glenn
 */
public class BoatDao {

    EntityManager em;

    public BoatDao(EntityManager em) {
        this.em = em;
    }

    public BoatDto toDto(Boat entity) {
        BoatDto b = new BoatDto(entity.getBoatId().intValue(), entity.getBoatName());
        b.setBoatImage(new BoatImageDto("defaultImage", entity.getBoatImage()));
        b.setCategory((new CategoryDao(em)).get(entity.getCategoryId()));
        b.setLatitude(entity.getLatitude());
        b.setLongitude(entity.getLongitude());
        return b;
    }

    public Boat fromDto(BoatDto dto) {


        Boat entity = new Boat();
        if (dto.getId() != null) {
            entity.setBoatId(dto.getId().shortValue());
        }
        entity.setBoatName(dto.getName());
        entity.setBoatDescription(dto.getDescription());
        entity.setBoatImage(dto.getBoatImage().getUrl());
        entity.setCategoryId((new CategoryDao(em)).fromDto(dto.getCategory()));

        return entity;
    }

    public void add(BoatDto b) {
        b.setId(boats.size());
        b.getCategory().setName(MockCategoryDao.get(b.getCategory().getId()).getName());

        boats.put(b.getId(), b);


        try {
            EntityTransaction t = em.getTransaction();
            try {
                t.begin();
                em.persist(null);
                t.commit();
            } finally {
                if (t.isActive()) {
                    t.rollback();
                }
            }
        } finally {
            em.close();
        }
    }

    public void save(BoatDto b) {
        boats.get(b.getId()).setName(b.getName());
        boats.get(b.getId()).getCategory().setName(MockCategoryDao.get(b.getCategory().getId()).getName());
        boats.get(b.getId()).getCategory().setId(b.getCategory().getId());
        boats.get(b.getId()).setBoatImage(b.getBoatImage());
    }

    public void delete(BoatDto b) {

        boats.remove(b.getId());
    }

    public BoatDto get(Integer id) {
        return boats.get(id);
    }

    public List<BoatDto> getAll() {

        return new ArrayList<BoatDto>(boats.values());
    }
}
